package com.carworld.model;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import com.carworld.model.base.BaseUserWithdrawal;
import com.carworld.utils.DateUtils;
import com.carworld.utils.DicUtil;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.TemplateData;
import com.jfinal.weixin.sdk.api.TemplateMsgApi;

/**
 * Generated by JFinal.
 */
@SuppressWarnings("serial")
public class UserWithdrawal extends BaseUserWithdrawal<UserWithdrawal> {
	public static final UserWithdrawal dao = new UserWithdrawal().dao();


     //保存提现记录鄢瑜晗重写版
    public String saveUserWithdrawal(String userId, String mobile, BigDecimal withdrawMoney,
                                     String accountNum,int takeType,BigDecimal userBalance2,
									 String takeName,String bankName,String bankAddress,String bankOwnerName) {
        String result = "y";
        SysUser user = SysUser.dao.findByIdInCache(userId);
        if (null != user) {
			System.out.println("手机号验证;"+mobile.equals(user.getMobile())+"ll"+mobile+"00"+user.getMobile());
            if (mobile.equals(user.getMobile())) {
                System.out.println("手机号验证通过");
                UserWithdrawal userWithdrawal = new UserWithdrawal();
                userWithdrawal.setId(getIds());
                userWithdrawal.setUserId(userId);
                userWithdrawal.setAccountNum(accountNum);
                userWithdrawal.setUserOfShop(user.getCompanyId());
                userWithdrawal.setWithdrawType(Integer.valueOf(user.getUserRole()));
                userWithdrawal.setWithdrawMethod(takeType);
                userWithdrawal.setWithdrawMoney(withdrawMoney);
                userWithdrawal.setWithdrawStatus(0);
                userWithdrawal.setUserBalance(userBalance2);
                userWithdrawal.setCreateTime(new Date());
                userWithdrawal.setUpdateTime(new Date());
				userWithdrawal.setTakeName(takeName);
				userWithdrawal.setBankName(bankName);
				userWithdrawal.setBankAddress(bankAddress);
				userWithdrawal.setBankOwnerName(bankOwnerName);
                userWithdrawal.save();

//                //给提款人发模板消息通知
//                ApiResult apiResultOfCustomer = TemplateMsgApi.send(TemplateData.New()
//                        .setTouser(user.getUserOpenid())// 消息接收者
//                        //.setTouser("oROsd0yDoWOUR7gN4WqLehPUVZAM")
//                        .setTemplate_id("thUi1j9Hkd7BzqRxVMFfLYgznAnkoh1YACkaNkJ2r2o")     //预约成功通知的模板id
//                        .setUrl("http://www.ntwk97.com/carworld_weixin/")
//                        // 模板参数
//                        .add("first", "您已经成功申请提现\n")
//                        .add("keyword1", DateUtils.getCurrentTime(new Date()), "#173177")
//                        .add("keyword2", withdrawMoney+"元" , "#173177")
//                        .add("remark", "您的提现申请已被受理，提现金额将在1-5个工作日到账。", "#173177")
//                        .build());
//                System.out.println("模板消息结果："+apiResultOfCustomer.getJson());

                String key = userId + mobile + withdrawMoney + userBalance2 + accountNum;
                // 加入缓存
                CacheKit.put(DicUtil.CACHE_USER_WITHDRAWAL, key, userWithdrawal);
                result="y";
            } else {
                System.out.println("手机号验证失败");
                result = "与预留手机号不符，请重新输入~";
            }
        } else {
            System.out.println("该用户不存在，请联共享平台管理员~");
            result = "该用户不存在，请联共享平台管理员~";
        }

        return result;
    }



	//返回提现列表
	public List<UserWithdrawal> findUserWithdrawalLsByCache(String userId,int index) {
		String sql="select s.name,sw.withdraw_money,sw.withdraw_status,DATE_FORMAT(sw.create_time,'%Y,%m,%d') from user_withdrawal sw left join sys_user s on sw.user_id=s.id  where sw.user_id=?  order by sw.create_time desc LIMIT ?,15";
		return Db.query(sql,userId,index);
	}

	//提现列表count

	public String getCountWiByUserId(String userId){
		String sql="select count(*) as countNum  from user_withdrawal sw where sw.user_id=?";
		return Db.queryStr(sql,userId);
	}

	/**
	 * 根据用户id查询提现总金额
	 * @param userId
	 * @return
	 */
	public UserWithdrawal findLastestByIdInCache(String userId) {
		String sqlString = "SELECT IFNULL(sum(sw.withdraw_money),0.00) as withdrawls  FROM user_withdrawal sw WHERE sw.user_id =? and sw.withdraw_status in (0,1)";
		return this.findFirst(sqlString,userId);
    } 
	
	public Record findLastRecordById(String userId) {
		String sqlString = "SELECT IFNULL(sum(sw.withdraw_money),0.00) as withdrawls  FROM user_withdrawal sw WHERE sw.user_id =? ";
		return  Db.findFirst(sqlString, userId);
    } 
	
	
	
	/**
	 * 保存提现记录
	 * @param userId
	 * @param mobile
	 * @param withdrawMoney
	 * @param userBalance
	 * @param accountNum
	 * @return
	 */
	public String saveUserWithdrawal(String userId, String mobile, BigDecimal withdrawMoney, BigDecimal userBalance,
			String accountNum) {
		String result = "";
		SysUser user = SysUser.dao.findByIdInCache(userId);
		if (null != user) {
			if (mobile.equals(user.getMobile())) {
				System.out.println("手机号验证通过");
				UserWithdrawal userWithdrawal = new UserWithdrawal();
				userWithdrawal.setId(getIds());
				userWithdrawal.setUserId(userId);
				userWithdrawal.setAccountNum(accountNum);
				userWithdrawal.setUserOfShop(user.getCompanyId());
				userWithdrawal.setWithdrawType(Integer.valueOf(user.getUserRole()));
				userWithdrawal.setWithdrawMethod(0);
				userWithdrawal.setWithdrawMoney(withdrawMoney);
				userWithdrawal.setWithdrawStatus(0);
				userWithdrawal.setUserBalance(userBalance);
				userWithdrawal.setCreateTime(new Date());
				userWithdrawal.setUpdateTime(new Date());
				userWithdrawal.save();
				
				//给提款人发模板消息通知
				ApiResult apiResultOfCustomer = TemplateMsgApi.send(TemplateData.New()
			            .setTouser(user.getUserOpenid())// 消息接收者
						//.setTouser("oROsd0yDoWOUR7gN4WqLehPUVZAM")
			            .setTemplate_id("thUi1j9Hkd7BzqRxVMFfLYgznAnkoh1YACkaNkJ2r2o")     //预约成功通知的模板id
			            .setUrl("http://www.ntwk97.com/carworld_weixin/")
			            // 模板参数
			            .add("first", "您已经成功申请提现\n")
			            .add("keyword1", DateUtils.getCurrentTime(new Date()), "#173177")
			            .add("keyword2", withdrawMoney+"元" , "#173177")
			            .add("remark", "您的提现申请已被受理，提现金额将在1-5个工作日到账。", "#173177")
			            .build());
			    System.out.println("模板消息结果："+apiResultOfCustomer.getJson());
			  
				String key = userId + mobile + withdrawMoney + userBalance + accountNum;
				// 加入缓存
				CacheKit.put(DicUtil.CACHE_USER_WITHDRAWAL, key, userWithdrawal);
				result="提现申请成功,我们将在三个工作日内为您处理，请您耐心等待~";
			} else {
				System.out.println("手机号验证失败");
				result = "与预留手机号不符，请重新输入~";
			}
		} else {
			System.out.println("该用户不存在，请联共享平台管理员~");
			result = "该用户不存在，请联共享平台管理员~";
		}

		return result;
	}

}
